package cn.xeblog.plugin.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.xeblog.commons.entity.IpRegion;
import cn.xeblog.plugin.entity.BaiDuDistrict;
import cn.xeblog.plugin.enums.ProvinceAbbreviation;
import com.google.gson.Gson;

/**
 * @author eleven
 * @date 2024/11/7 10:58
 * @apiNote
 */
public class IpRegionUtil {
    private static Gson gson = new Gson();

    private static final String BAIDU_DISTRICT = "https://qifu.baidu.com/ip/local/geo/v1/district";
    private static String hostIp() {
        String getIpUrl = BAIDU_DISTRICT;
        String result = HttpUtil.get(getIpUrl);
        BaiDuDistrict baiDuDistrict = gson.fromJson(result, BaiDuDistrict.class);
        return baiDuDistrict.getIp();
    }

    private static BaiDuDistrict ipRegion(String ip) {
        String getIpUrl = BAIDU_DISTRICT;
        String result = HttpUtil.get(StrUtil.format("{}?ip={}", getIpUrl, ip));
        return gson.fromJson(result, BaiDuDistrict.class);

    }

    public static IpRegion ipRegion() {
        String ip = hostIp();
        BaiDuDistrict baiDuDistrict = ipRegion(ip);
        BaiDuDistrict.DataBean data = baiDuDistrict.getData();
        IpRegion ipRegion = new IpRegion();
        ipRegion.setIp(baiDuDistrict.getIp());
        ipRegion.setCountry(data.getCountry());
        ipRegion.setProvince(data.getProv());
        ipRegion.setCity(data.getCity());
        ipRegion.setArea(data.getDistrict());
        ipRegion.setIsp(data.getIsp());
        return ipRegion;
    }
}
